var client = require("../DAOImpl/mongodb");
var dataConfig = require("../config/database.json");
var host = dataConfig.host;
var database = dataConfig.db;
var db = new client(host, database);
var status = require("../config/status.json");
var notification = require('../private/notification');

function sleep(milliSecond) {
	var startTime = new Date().getTime();
	console.log(startTime);
	while (new Date().getTime() <= milliSecond + startTime) {
	}
	console.log(new Date().getTime());
}
/*
 * @req.body cus_lat cus_lng cus_id {"cus_lat":
 * 31.202818,"cus_lng":121.557706,"cus_id":1}
 */
function bookNow(req, res, next) {
	console.log('bookNow');
	console.log(req.body.cus_lng + '  ' + req.body.cus_lat);
	var result = new Object();
	var selector = new Object();
	var info = new Obejct();
	info.cus_id = req.body.cus_id;
	info.status = status.ORDERSTATUS.CUSTOMERREQUEST.VALUE;

	db.insert(dataConfig.col_order, info, function(err1, doc_order) {
		if (err1 ) {
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
		} else {

			// send notification to the driver
			db.find(dataConfig.col_driver, {}, {fields:{_id :1}}, function(err3,  doc) {
				if (err3 ) {
					console.log(err3);
				} else {
					var message = new Object();
					message.cus_id = req.body.cus_id;
					message.cus_lat = req.body.cus_lat;
					message.cus_lag = req.body.cus_lag;
					var notifi = new notification(doc, message, function(err,
							req, res, data) {
						if (err) {
							console.log(err);
						} else {
							console.log('notification is done!');
							result.status = status.SUCCESS.VALUE;
							result.order_id = doc_order._id;
							res.send(result);
						}
					});
				}
			});
		}
	});
	return next();
}

/*
 * @req.body: cus_id {'cus_id': '1'}, page
 */

function showOrder(req, res, next) {
	var result = new Object();

	var query1 = new Object();
	query1.cus_info = new Object();
	query1.cus_info._id = req.body.cus_id;
	query1.status = status.ORDERSTATUS.WAITING.VALUE;
	db.find(dataConfig.col_order, query1, function(err1, doc_waiting){
		if(err1){
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
		}else{
			var query2 = new Object();
			query2.cus_info = new Object();
			query2.cus_info._id = req.body.cus_id;
			query2.status = status.ORDERSTATUS.CUSTOMERACCEPT.VALUE;
			db.find(dataConfig.col_order, query2, function(err3, doc_success){
				if(err3){
					result.status = status.SYSTEMERROR.VALUE;
					res.send(result);
				}else{
					var query3 = new Object();
					var options = new Object();
					query3.$or = [{cus_info:{_id:req.body.cus_id},status:status.ORDERSTATUS.CUSTOMERACCEPT.VALUE},
					              {cus_info:{_id:req.body.cus_id},status:status.ORDERSTATUS.WAITING.VALUE}];
					options.skip =  (req.body.page - 1) * 10;
					db.find(dataConfig.col_order, query3, options, function(err4, doc){
						if(err4){
							result.status = status.SYSTEMERROR.VALUE;
							res.send(result);
						}else{
							var maxPage = (doc.length - doc.length %10 ) / 10 + 1;
							result.maxPage = maxPage;
							result.order_waiting_num = doc_waiting.length,
							result.order_success_num = doc_success.length;
							result.orders = doc;
							result.status = status.SUCCESS.VALUE;
							res.send(result);
						}
					});		
				}
			});
		}
	});
	return next();
}

/*
 * @req.body: cus_id ,page
 * {'cus_id': '1'}
 */
function showHisOrder(req, res, next) {
	var result = new Object();
	var query1 = new Object();
	query1.cus_info = new Object();
	query1.cus_info._id = req.body.cus_id;
	db.find(dataConfig.col_order, query1 ,function(err1, docs) {
		if (err1) {
				result.status = status.SYSTEMERROR.VALUE;
				res.send(result);
			} else {
				console.log('all doc is ' + JSON.stringify(docs));
				var count = 0;
				for(var index in docs){
					if(docs[index].status === status.ORDERSTATUS.CUSTOMERACCEPT.VALUE){
						count ++;
					}
				}
				result.order_history = new Array();
				var maxPage = (docs.length - docs.length %10 ) / 10 + 1;
				var pageNumber = 10 ;
				if(maxPage == req.body.page){
					pageNumber = docs.length % 10;
				}
				for(var i = 0; i< pageNumber; i ++){
					result.order_history[i] = docs[(req.body.page-1) * 10 + i];
				}
				
				result.maxPage = maxPage; 
				result.succ_percent = count / docs.length;
				result.status = status.SUCCESS.VALUE;
				res.send(result);
			}
		});
	return next();
}

/*
 * cancel the order if the order is created. @path /cancelorder @req.body:
 * cus_id {'order_id': '1'}
 */

function cancelOrder(req, res, next) {
	var result = new Object();
	var selector = new Object();
	var document = new Object();

	selector.cus_id = req.body.cus_id;
	selector.stauts = {
		$ne : status.ORDERSTATUS.CUSTOMERACCEPT.VALUE
	};
	document.status = status.ORDERSTATUS.CANCEL.VALUE;

	db.find(dataConfig.col_driver, {}, {
		fields : {
			_id : 1
		}
	}, function(err1, userIds) {
		if (err1) {
			console.log(err1);
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
		} else {
			var message = new Object();
			var notifi = new notification(userIds, message, function(err, req, res,
					data) {
				if (err) {
					console.log(err);
					result.status = status.SYSTEMERROR.VALUE;
					result.err = err;
					res.send(result);
				} else {
					console.log('notification is done!');
					db.update(dadaConfig.col_order, selector, document,
							function(err3, doc) {
								if (err3) {
									result.status = status.SYSTEMERROR.VALUE;
									res.send(result);
								} else {
									result.status = status.SUCCESS.VALUE;
									res.send(result);
								}
							});
				}
			});
		}
	});
	return next;
}

/*
 * @req.body
 * cus_id
 * setupTime
 * fromAddrLat
 * fromAddrLng
 * toAddrLat
 * toAddrLng
 */
function orderTaxi(req, res, next){
	var result = new Object();
	var info = new Object();
	info.cus_id = req.body.cus_id;
	info.setupTime = req.body.setupTime;
	info.fromAddrLat = req.body.fromAddrLat;
	info.fromAddrLng = req.body.fromAddrLng;
	info.toAddrLat = req.body.toAddrLat;
	info.toAddrLng = req.body.toAddrLng;
	info.status = status.ORDERSTATUS.CUSTOMERREQUEST.VALUE;
	
	db.insert(dataConfig.col_order, info, function(err, doc){
		if(err){
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
		}else{
			// send notification to the driver
			db.find(dataConfig.col_driver, {}, {fields:{_id :1}}, function(err3, userIds) {
				if(err3){
					result.status = status.SYSTEMERROR.VALUE;
					res.send(result);
				}else{
					var message = new Object();
					message.order = new Object();
					message.order = doc;
					var notifi = new notification(userIds, message, function(err, req, res,
							data) {
						if(err){
							result.status = status.SYSTEMERROR.VALUE;
							res.send(result);
						}else{
							result.status = status.SUCCESS.VALUE;
							res.send(result);
						}
					});	
				}
			});	
		}
	});
	return next;
}
exports.services = [ bookNow, showOrder, showHisOrder, cancelOrder, orderTaxi ];